package com.xken.example.service.impl;

import com.xken.example.dao.VideoRepository;
import com.xken.example.entity.Video;
import com.xken.example.service.VideoService;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class VideoServiceImpl implements VideoService {
    @Autowired
    private VideoRepository VideoRepository;

    @Override
    public long count() {
        return VideoRepository.count();
    }

    @Override
    public Video save(Video Video) {
        return VideoRepository.save(Video);
    }

    @Override
    public void delete(Video Video) {
        VideoRepository.delete(Video);//        VideoRepository.deleteById(Video.getSkuId());
    }

    @Override
    public Iterable<Video> getAll() {
        return VideoRepository.findAll();
    }

    @Override
    public List<Video> getByName(String name) {
        List<Video> list = new ArrayList<>();
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("name", name);
        Iterable<Video> iterable = VideoRepository.search(matchQueryBuilder);
        iterable.forEach(e -> list.add(e));
        return list;
    }

    @Override
    public Page<Video> pageQuery(Integer pageNo, Integer pageSize, String kw) {
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchPhraseQuery("name", kw)).withPageable(PageRequest.of(pageNo, pageSize)).build();
        return VideoRepository.search(searchQuery);
    }

    @Override
    public Page<Video> pageQueryByLabels(Integer pageNo, Integer pageSize, String labels) {
//可以模糊匹配
        //        SearchQuery searchQuery = new NativeSearchQueryBuilder().withFilter(QueryBuilders.matchPhraseQuery("labels", labels)).withPageable(PageRequest.of(pageNo, pageSize)).build();
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withFilter(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("labels", labels)))
                .withPageable(PageRequest.of(pageNo, pageSize)).build();
        return VideoRepository.search(searchQuery);
    }

}